//
//  LSSocketManeger.m
//  LookScore
//
//  Created by wws on 2018/3/23.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSSocketManeger.h"
#import <SRWebSocket.h>

@interface LSSocketManeger()<SRWebSocketDelegate>

@property (nonatomic, strong) SRWebSocket * webSocket;
@property (nonatomic, assign) LSSocketStatus ls_socketStatus;
@property (nonatomic, weak) NSTimer * timer;
/***/
@property (nonatomic, copy) NSString * urlStr;


@end
@implementation LSSocketManeger{
//    NSInteger _reconnectCounter;
    
}

+ (instancetype)shareManeger{
    static LSSocketManeger * instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.overtime = 1;
        instance.reconnectCount = 10;
    });
    return instance;
}
- (void)ls_open:(NSString *)urlStr connect:(LSSocketDidConnectBlock)connect receive:(LSSocketDidReciveBlock)receive failure:(LSSocketDidFailBlock)failure{
    [LSSocketManeger shareManeger].connect = connect;
    [LSSocketManeger shareManeger].receive = receive;
    [LSSocketManeger shareManeger].failure = failure;
    [self ls_open:urlStr];
    
}
- (void)ls_close:(LSSocketDidCloseBlock)close{
    [LSSocketManeger shareManeger].close = close;
    [self ls_close];
}

- (void)ls_send:(id)data{
    switch ([LSSocketManeger shareManeger].ls_socketStatus) {
        case LSSocketStatusConnected:
        case LSSocketStatusReceived:{
            MyLog(@"发送中");
            [self.webSocket send:data];
            break;
        }
        case LSSocketStatusFailed:
            MyLog(@"发送失败");
            break;
            
        case LSSocketStatusClosedByServer:
            MyLog(@"已经关闭");
            break;
            case LSSocketStatusClosedByUser:
            //关闭
            break;
        default:
            break;
    }
    
}
#pragma mark ---private
- (void)ls_open:(id)params{
    NSString * urlStr = nil;
    if ([params isKindOfClass:[NSString class]]) {
        urlStr = (NSString *)params;
    }else if([params isKindOfClass:[NSTimer class]]){
        NSTimer * timer = (NSTimer *)params;
        urlStr = [timer userInfo];
    }else{
        urlStr = @"";
    }
    [LSSocketManeger shareManeger].urlStr = urlStr;
    [self.webSocket close];
    self.webSocket.delegate = nil;
    self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    self.webSocket.delegate = self;
    [self.webSocket open];
}

- (void)ls_close{
    [self.webSocket close];
    self.webSocket = nil;
    [self.timer invalidate];
    self.timer = nil;
    
}

- (void)ls_reconnect{
    //计数+1
    if (_reconnectCounter < self.reconnectCount-1) {
        _reconnectCounter ++;
        NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:self.overtime target:self selector:@selector(ls_open:) userInfo:self.urlStr repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        self.timer = timer;
    }else{
        MyLog(@"Websocket Reconnected Outnumber ReconnectCount");
        if (self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        return;
    }
    
}

#pragma mark -- SRWebSocketDelegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
//     MyLog(@"Websocket Connected");
    [LSSocketManeger shareManeger].connect ? [LSSocketManeger shareManeger].connect() : nil;
    [LSSocketManeger shareManeger].ls_socketStatus = LSSocketStatusConnected;
    _reconnectCounter = 0;
    
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    MyLog(@":( Websocket Failed With Error %@", error);
    [LSSocketManeger shareManeger].ls_socketStatus = LSSocketStatusFailed;
    [LSSocketManeger shareManeger].failure ? [LSSocketManeger shareManeger].failure(error) : nil;
    [self ls_reconnect];
    
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
//    MyLog(@":( Websocket Receive With message %@", message);
    [LSSocketManeger shareManeger].ls_socketStatus = LSSocketStatusReceived;
    [LSSocketManeger shareManeger].receive ? [LSSocketManeger shareManeger].receive(message,LSSocketReceiveTypeForMessage) : nil;
    
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
    MyLog(@"Closed Reason:%@  code = %zd",reason,code);
    if (reason) {
        [LSSocketManeger shareManeger].ls_socketStatus = LSSocketStatusClosedByServer;
        //重连
        [self ls_reconnect];
    }else{
        
        [LSSocketManeger shareManeger].ls_socketStatus = LSSocketStatusClosedByUser;
        
    }
    [LSSocketManeger shareManeger].close ? [LSSocketManeger shareManeger].close(code, reason, wasClean): nil;
    self.webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
    [LSSocketManeger shareManeger].receive ? [LSSocketManeger shareManeger].receive(pongPayload,LSSocketReceiveTypeForPong) : nil;
    
    
}

- (void)dealloc{
    [self ls_close];
    
}

@end
